
package com.ifcar.app.adapter;

import com.ifcar.app.activity.common.CommentFragment;
import com.ifcar.app.model.Comment;
import com.ifcar.app.util.GroupAdapter;
import com.ifcar.app.util.ModelUtils;
import com.ifcar.app.util.StringUtil;
import com.ifcar.app.util.ThemeSettingsHelper;
import com.ifcar.app.view.FloorsView;
import com.ifcar.app.view.FloorsView.FloorViewHolder;
import com.ifcar.app.activity.R;
import com.netease.util.Pair;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CommonCommentAdapter extends GroupAdapter<String, Map<String, Object>> implements
        FloorsView.FloorBinder, OnClickListener {
    static final int MSG_EXPANDS_HIDE = 0;

    LayoutInflater mLayoutInflater;

    ThemeSettingsHelper mThemeSettingsHelper;

    float mTextSize;

    private Context mContext;

    private String mBoardId;
    
    private FloorViewHolder mFloorViewHolder;

    public CommonCommentAdapter(Context context, List<Pair<String, List<Map<String, Object>>>> list, String boardId) {
        super(list);
        mContext = context;
        mLayoutInflater = LayoutInflater.from(context);
        mThemeSettingsHelper = ThemeSettingsHelper.getThemeSettingsHelper(context);
        mBoardId = boardId;
        mFloorViewHolder = new FloorViewHolder();
    }

    public void setTextSize(float size) {
        if (mTextSize != size) {
            mTextSize = size;
            notifyDataSetChanged();
        }
    }

    public Context getContext() {
        return mContext;
    }

    @Override
    public View getGroupView(int groupPosition, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = mLayoutInflater.inflate(R.layout.comment_group, parent, false);
        }
        ImageView img = (ImageView) convertView.findViewById(R.id.comment_group_img);
        TextView msg = (TextView) convertView.findViewById(R.id.comment_group_msg);
        if (getChildrenCount(groupPosition) > 0) {
            msg.setVisibility(View.GONE);
        } else {
            msg.setVisibility(View.VISIBLE);
        }
        
        String tag = getGroup(groupPosition);
        
        if (CommentFragment.TAG_HOT.equals(tag)) {
            mThemeSettingsHelper.setImageViewSrc(getContext(), img, R.drawable.hot_comment);
        } else if (CommentFragment.TAG_TOP.equals(tag)){
            mThemeSettingsHelper.setImageViewSrc(getContext(), img, R.drawable.top_comment);
        } else {
            mThemeSettingsHelper.setImageViewSrc(getContext(), img, R.drawable.latest_comment);
        }
        
        
        
        return convertView;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, View convertView,
            ViewGroup parent) {
        if (convertView == null) {
            convertView = mLayoutInflater.inflate(R.layout.comment_floor_last, null);
            FloorsView floors = (FloorsView) convertView.findViewById(R.id.sub_floors);
            floors.setFloorBinder(this);
            floors.setFloorViewHolder(mFloorViewHolder);
        }

        TextView username = (TextView) convertView.findViewById(R.id.last_floor_username);
        TextView date = (TextView) convertView.findViewById(R.id.last_floor_date);
        TextView content = (TextView) convertView.findViewById(R.id.last_floor_content);
        TextView orig = (TextView)convertView.findViewById(R.id.last_floor_orig);
        orig.setVisibility(View.GONE);
        FloorsView floors = (FloorsView) convertView.findViewById(R.id.sub_floors);

        Map<String, Object> data = getChild(groupPosition, childPosition);
        if (data == null) {
            data = new HashMap<String, Object>();
        }

        int last = getLastFloorNum((Map<String, Object>) data);
        if (last < 0) {
            return convertView;
        }

        // 取出最后层绑定
        Map<String, Object> map = (Map<String, Object>) ModelUtils.getValue(data, String
                .valueOf(last));

        username.setText((String) ModelUtils.getValue(map, Comment.PARAM_F));
        date.setText(StringUtil.getDate((String) ModelUtils.getValue(map, Comment.PARAM_T)));
        content.setText((String) ModelUtils.getValue(map, Comment.PARAM_B));
        content.setTextSize(mTextSize);
        
        floors.setFloorColor(mThemeSettingsHelper.getThemeColor(mContext, R.color.floor).getDefaultColor());
        floors.setFloorStrokeColor(mThemeSettingsHelper.getThemeColor(mContext, R.color.floor_stroke).getDefaultColor());
        floors.setFloorsValue(data);
        return convertView;
    }

    @Override
    public void bindFloor(ViewGroup floor, int position, Object data, int floorCount) {
//        mThemeSettingsHelper.setViewBackgroud(getContext(), floor, R.drawable.comment_bk);
        
        int last = getLastFloorNum((Map<String, Object>) data);
        if (last <= 1) {
            floor.findViewById(R.id.hide_floor_content).setVisibility(View.GONE);
            floor.findViewById(R.id.show_floor_content).setVisibility(View.GONE);
            return;
        }

        View hideView = floor.findViewById(R.id.hide_floor_content);
        int hide = getHidePosition((Map<String, Object>) data);
        if (hide >= 0) {
            // 说明有隐藏楼层
            if (position == hide) {
                // 当前是隐藏楼层
                floor.findViewById(R.id.show_floor_content).setVisibility(View.GONE);
                hideView.setVisibility(View.VISIBLE);
                hideView.setTag(data);

                TextView hideText = (TextView) hideView.findViewById(R.id.hide_text);
                View hidePb = hideView.findViewById(R.id.hide_pb);

                boolean isExpanding = isExpanding((Map<String, Object>) data);
                if (isExpanding) {
                    hidePb.setVisibility(View.VISIBLE);
                    hideText.setText(R.string.comment_hide_expanding);
                } else {
                    hidePb.setVisibility(View.GONE);
                    hideText.setText(R.string.comment_show_hide);
                }

                hideText.setTextSize(mTextSize);
                return;
            } else if (position > hide) {
                // 当前是隐藏楼层后面的层
                position = position + (last - 5);
            }
        }

        Map<String, Object> map = (Map<String, Object>) data;

        hideView.setTag(null);
        hideView.setVisibility(View.GONE);
        floor.findViewById(R.id.show_floor_content).setVisibility(View.VISIBLE);

        TextView username = (TextView) floor.findViewById(R.id.floor_username);
        TextView num = (TextView) floor.findViewById(R.id.floor_num);
        TextView content = (TextView) floor.findViewById(R.id.floor_content);

        map = (Map<String, Object>) ModelUtils.getValue(map, String.valueOf(position + 1));
        username.setText((String) ModelUtils.getValue(map, Comment.PARAM_F));

        num.setText(String.valueOf(position + 1));
        content.setText((String) ModelUtils.getValue(map, Comment.PARAM_B));
        content.setTextSize(mTextSize);
    }

    @Override
    public View createFloorContentView(Object datas, ViewGroup parent) {
        View floor = mLayoutInflater.inflate(R.layout.comment_floor_normal, parent, false);
        View hideView = floor.findViewById(R.id.hide_floor_content);
        hideView.setOnClickListener(this);
        return floor;
    }

    @Override
    public int getFloorCount(Object data) {
        Map<String, Object> map = (Map<String, Object>) data;
        if (map == null || map.size() == 0) {
            return 0;
        }

        int count = map.size();

        // 需要先减去展开标识位
        if (map.containsKey(Comment.PARAM_EXPANDING)) {
            count--;
        }

        int hide = getHidePosition(map);
        if (hide >= 0) {
            // 最后一层已经已经绑定过，还要加上隐藏楼层,这里需要再减1，因为non也是在这个map里
            return count - 1;
        }

        // 最后一层已经已经绑定过
        return count - 1;
    }

    /**
     * 返回最后楼层号
     * 
     * @param data
     * @return 返回-1说明没有楼层
     */
    public int getLastFloorNum(Map<String, Object> data) {
        if (data == null || data.size() == 0) {
            return -1;
        }

        String non = (String) ModelUtils.getValue(data, Comment.PARAM_NON);
        if (TextUtils.isEmpty(non)) {
            return data.size();
        }

        try {
            return Integer.valueOf(non);
        } catch (Exception e) {
            return data.size();
        }
    }

    /**
     * 返回隐藏楼层号
     * 
     * @param data
     * @return 返回-1说明没有隐藏楼层
     */
    int getHidePosition(Map<String, Object> data) {
        int non = -1;
        String nonStr = (String) ModelUtils.getValue(data, Comment.PARAM_NON);
        if (!TextUtils.isEmpty(nonStr)) {
            try {
                non = Integer.valueOf(nonStr);
            } catch (Exception e) {
            }
        }

        // 当有non时,说明有隐藏
        if (non != -1) {
            // 都返回2，这个要和后台接口参数保持一致
            return 2;
        }

        return -1;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.hide_floor_content:
                Map<String, Object> data = (Map<String, Object>) v.getTag();
                expandHide(data);
                break;

            default:
                break;
        }

    }

    boolean isExpanding(Map<String, Object> data) {
        Object xxx = ModelUtils.getValue(data, Comment.PARAM_EXPANDING);
        if (xxx != null && xxx instanceof Boolean) {
            return (Boolean) xxx;
        }
        return false;
    }

    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            CommonCommentAdapter.this.handleMessage(msg);
        }

    };

    /**
     * 以下方法是用于展开跟帖，先不删除
     */
    void expandHide(final Map<String, Object> data) {
        if (data == null) {
            return;
        }

        boolean isExpanding = isExpanding(data);
        if (isExpanding) {
            return;
        }

        int last = getLastFloorNum(data);
        if (last < 1) {
            return;
        }
        final String boardid = mBoardId;
        if (TextUtils.isEmpty(boardid)) {
            return;
        }

        // 取最后一层的pi,拆开得到p和d
        Map<String, Object> map = (Map<String, Object>) ModelUtils.getValue(data, String
                .valueOf(last));

        final String pi = (String) ModelUtils.getValue(map, Comment.PARAM_PI);
        if (TextUtils.isEmpty(pi)) {
            return;
        }

        String[] ss = pi.split("_");
        if (ss == null || ss.length != 2) {
            return;
        }

        final String d = ss[0];
        if (TextUtils.isEmpty(d)) {
            return;
        }

        final String p = ss[1];
        if (TextUtils.isEmpty(p)) {
            return;
        }

        // 标识当前楼正在展开
        data.put(Comment.PARAM_EXPANDING, true);
        new Thread() {
            @Override
            public void run() {
                // try {
                // Thread.sleep(3000);
                // } catch (InterruptedException e) {
                // // TODO Auto-generated catch block
                // e.printStackTrace();
                // }
                Map<String, Object> result = new HashMap<String, Object>();
                result.put("data", data);
                result.put("bd", Comment.expand(boardid, d, p, getContext()));
                Message msg = mHandler.obtainMessage(MSG_EXPANDS_HIDE);
                msg.obj = result;
                mHandler.sendMessage(msg);
            }

        }.start();
        notifyDataSetChanged();
    }

    void handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_EXPANDS_HIDE: {
                Map<String, Object> result = (Map<String, Object>) msg.obj;
                if (result == null) {
                    return;
                }

                Map<String, Object> data = (Map<String, Object>) ModelUtils
                        .getValue(result, "data");
                if (data == null) {
                    return;
                }

                boolean isExpanding = isExpanding(data);
                if (!isExpanding) {
                    return;
                }

                Map<String, Object> bd = (Map<String, Object>) ModelUtils.getValue(result, "bd");

                if (bd != null && bd.size() > 0) {
                    data.clear();
                    data.putAll(bd);

                } else {
                    // 重置展开标识
                    data.remove(Comment.PARAM_EXPANDING);
                    Toast.makeText(getContext(), "展开跟帖失败", Toast.LENGTH_SHORT).show();
                }

                notifyDataSetChanged();

                break;
            }
            default:
                break;
        }
    }
}
